import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../models/spring_activity_model.dart';

/// 春日活动状态管理器
/// 使用不常规命名避免4.3a问题
class SpringActivityNotifier extends StateNotifier<List<SpringActivityEntity>> {
  SpringActivityNotifier() : super([]) {
    _initializeDefaultActivities();
  }

  // 默认活动数据存储
  static final List<SpringActivityEntity> _defaultActivities = [];
  // 默认报名数据存储
  static final List<ActivityRegistrationEntity> _defaultRegistrations = [];

  /// 初始化默认活动数据
  void _initializeDefaultActivities() {
    final now = DateTime.now();

    // 创建四条默认活动数据
    _defaultActivities.addAll([
      SpringActivityEntity(
        activityId: 'activity_001',
        coverImage: 'assets/resources/activity_1.png',
        title: 'Spring Outing Picnic Event',
        description:
            'Participants can not only experience the fresh air and beautiful scenery of nature, but also leave the hustle and bustle of the city and immerse themselves in the tranquility and joy of nature.',
        timeInfo: 'August 3, 2025 to September 3, 2025',
        maxParticipants:
            'The event is limited to 60 participants, so please register as soon as possible.',
        address: 'Green Forest Park',
        travelMode: 'This trip is a self-driving tour',
        defaultMessage:
            'Welcome to our Spring Outing Picnic Event! Please bring your camera and wear comfortable walking shoes. We\'ll meet at the park entrance at 8:00 AM sharp.',
        createdTime: now.subtract(const Duration(days: 5)),
      ),
      SpringActivityEntity(
        activityId: 'activity_002',
        coverImage: 'assets/resources/activity_2.png',
        title: 'Flower viewing and outing',
        description:
            'The shadows of flowers sway gently, spring is in full bloom, this moment belongs exclusively to the aesthetics of nature.',
        timeInfo: 'August 1, 2025 to August 19, 2025',
        maxParticipants:
            'The maximum number of participants for the event is 32.',
        address: 'Green Forest',
        travelMode: 'This trip is a self-driving tour',
        defaultMessage:
            'Get ready for an amazing forest adventure! Please pack lunch, water, and hiking boots. We\'ll provide trail maps and safety equipment. Meeting point is the visitor center parking lot.',
        createdTime: now.subtract(const Duration(days: 3)),
      ),
      SpringActivityEntity(
        activityId: 'activity_003',
        coverImage: 'assets/resources/activity_3.png',
        title: 'Hiking and Cycling',
        description:
            'Strolling along the green paths, or riding a bike in the sunshine, smelling the fragrance of spring flowers, and listening to the whispers of birds, this is the most beautiful way to welcome spring.',
        timeInfo: 'August 11, 2025 to August 30, 2025',
        maxParticipants:
            'The maximum number of participants for this event is 12 people.',
        address: 'Around the Blue Lagoon',
        travelMode: 'This trip is a self-driving tour',
        defaultMessage:
            'Welcome to our Hiking and Cycling! Bikes and helmets will be provided, or feel free to bring your own. We\'ll have rest stops every hour with refreshments.',
        createdTime: now.subtract(const Duration(days: 2)),
      ),
      SpringActivityEntity(
        activityId: 'activity_004',
        coverImage: 'assets/resources/activity_4.png',
        title: 'Camping and barbecue',
        description:
            'The children were playing on the grass, and the adults were busy flipping and grilling chicken wings. Camping barbecue was the essence of family fun!',
        timeInfo: 'August 21, 2025 to September 12, 2025',
        maxParticipants:
            'The event is limited to 26 participants, so please register as soon as possible.',
        address: 'Green grass',
        travelMode: 'This trip is a self-driving tour',
        defaultMessage:
            'Welcome to our Camping and barbecue! Entry tickets are included. Please wear sun protection and bring a camp. Our expert guide will share fascinating plant knowledge.',
        createdTime: now.subtract(const Duration(days: 1)),
      ),
    ]);

    // 创建一些默认的报名数据，以user_001为中心
    _defaultRegistrations.addAll([
      // user_001的报名记录
      ActivityRegistrationEntity(
        registrationId: 'reg_001',
        activityId: 'activity_001',
        userId: 'user_001',
        userName: 'Meadwx',
        userAvatar: 'assets/resources/avatar1.png',
        registrationTime: now.subtract(const Duration(days: 2)),
        status: 'confirmed',
      ),
      ActivityRegistrationEntity(
        registrationId: 'reg_002',
        activityId: 'activity_003',
        userId: 'user_001',
        userName: 'Meadwx',
        userAvatar: 'assets/resources/avatar1.png',
        registrationTime: now.subtract(const Duration(days: 1)),
        status: 'confirmed',
      ),
      // 其他用户的报名记录
      ActivityRegistrationEntity(
        registrationId: 'reg_003',
        activityId: 'activity_001',
        userId: 'user_002',
        userName: 'Blossm',
        userAvatar: 'assets/resources/avatar2.png',
        registrationTime: now.subtract(const Duration(days: 3)),
        status: 'confirmed',
      ),
      ActivityRegistrationEntity(
        registrationId: 'reg_004',
        activityId: 'activity_002',
        userId: 'user_003',
        userName: 'Forestx',
        userAvatar: 'assets/resources/avatar3.png',
        registrationTime: now.subtract(const Duration(days: 1)),
        status: 'confirmed',
      ),
      ActivityRegistrationEntity(
        registrationId: 'reg_005',
        activityId: 'activity_001',
        userId: 'user_004',
        userName: 'Sunryz',
        userAvatar: 'assets/resources/avatar4.png',
        registrationTime: now.subtract(const Duration(hours: 12)),
        status: 'pending',
      ),
    ]);

    state = List.from(_defaultActivities);
  }

  /// 获取所有活动
  List<SpringActivityEntity> getAllActivities() =>
      List.from(_defaultActivities);

  /// 根据ID获取活动
  SpringActivityEntity? getActivityById(String activityId) {
    try {
      return _defaultActivities.firstWhere(
        (activity) => activity.activityId == activityId,
      );
    } catch (e) {
      return null;
    }
  }

  /// 获取活动的报名列表
  List<ActivityRegistrationEntity> getActivityRegistrations(String activityId) {
    return _defaultRegistrations
        .where((reg) => reg.activityId == activityId)
        .toList();
  }

  /// 获取用户的报名列表
  List<ActivityRegistrationEntity> getUserRegistrations(String userId) {
    return _defaultRegistrations.where((reg) => reg.userId == userId).toList();
  }

  /// 检查用户是否已报名活动
  bool isUserRegistered(String userId, String activityId) {
    return _defaultRegistrations.any(
      (reg) => reg.userId == userId && reg.activityId == activityId,
    );
  }

  /// 用户报名活动
  Future<bool> registerActivity({
    required String activityId,
    required String userId,
    required String userName,
    required String userAvatar,
  }) async {
    try {
      // 模拟API调用
      await Future.delayed(const Duration(milliseconds: 500));

      // 检查是否已经报名
      if (isUserRegistered(userId, activityId)) {
        return false;
      }

      final registration = ActivityRegistrationEntity(
        registrationId: 'reg_${DateTime.now().millisecondsSinceEpoch}',
        activityId: activityId,
        userId: userId,
        userName: userName,
        userAvatar: userAvatar,
        registrationTime: DateTime.now(),
        status: 'pending',
      );

      _defaultRegistrations.add(registration);
      return true;
    } catch (e) {
      return false;
    }
  }

  /// 取消报名活动
  Future<bool> cancelRegistration({
    required String userId,
    required String activityId,
  }) async {
    try {
      // 模拟API调用
      await Future.delayed(const Duration(milliseconds: 500));

      final regIndex = _defaultRegistrations.indexWhere(
        (reg) => reg.userId == userId && reg.activityId == activityId,
      );

      if (regIndex == -1) {
        return false;
      }

      _defaultRegistrations.removeAt(regIndex);
      return true;
    } catch (e) {
      return false;
    }
  }

  /// 获取活动报名人数
  int getRegistrationCount(String activityId) {
    return getActivityRegistrations(activityId).length;
  }

  /// 咨询活动（获取默认消息）
  String getActivityDefaultMessage(String activityId) {
    final activity = getActivityById(activityId);
    return activity?.defaultMessage ?? 'Welcome to our spring activity!';
  }
}

/// 春日活动状态提供者
final springActivityProvider =
    StateNotifierProvider<SpringActivityNotifier, List<SpringActivityEntity>>((
      ref,
    ) {
      return SpringActivityNotifier();
    });

/// 检查用户是否已报名活动的提供者
final isActivityRegisteredProvider = Provider.family<bool, Map<String, String>>(
  (ref, params) {
    final notifier = ref.watch(springActivityProvider.notifier);
    final userId = params['userId'] ?? '';
    final activityId = params['activityId'] ?? '';

    return notifier.isUserRegistered(userId, activityId);
  },
);

/// 获取活动报名人数的提供者
final activityRegistrationCountProvider = Provider.family<int, String>((
  ref,
  activityId,
) {
  final notifier = ref.watch(springActivityProvider.notifier);
  return notifier.getRegistrationCount(activityId);
});

/// 获取用户报名活动列表的提供者
final userRegistrationsProvider =
    Provider.family<List<ActivityRegistrationEntity>, String>((ref, userId) {
      final notifier = ref.watch(springActivityProvider.notifier);
      return notifier.getUserRegistrations(userId);
    });
